import gzip
import os
import re
import sys
import urllib
import tarfile
import shutil
import subprocess

# file handling
def compress(file):
    #if config.get('global', 'gzip') == True:
    r_file = open(file, 'r')
    w_file = gzip.GzipFile(file + '.gz', 'w', 9)
    w_file.write(r_file.read())
    w_file.flush()
    w_file.close()
    r_file.close()
    os.unlink(file) #We don't need the file now

def read_as_string(file):
    # read the file
    f = open(file, "r")
    content = f.read()
    f.close()
    return content

def append_string(content, file, gzip=False):
    if os.path.exists(file):
        # ensure that we can write the file
        os.chmod(file, 0644)
    # write the string
    f = open(file, "w")
    f.write(content)
    f.close()
    if gzip:
        compress(file)

def set_string(content, file):
    if os.path.exists(file):
        # ensure that we can write the file
        os.chmod(file, 0644)
    f = open(file, "w")
    

def download_file(url, local_file):
    #remoteFileName = u"http://example.com/a.txt" # set the url here
    #localFileName = u"c:\\items.txt"
    log("Downloading %s into %s..." % (url, local_file))
    urllib.urlretrieve(url, local_file)


def untar(file_path, target_directory):
    tar = tarfile.open(file_path)
    tar.extractall(target_directory)
    tar.close()

def shell_exec(cmd, printcmd=False):
    if printcmd:
        log(cmd)
    proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    output = proc.communicate()[0]
    return output.strip()

        
def get_user_home(user):
    user_home = shell_exec("cat /etc/passwd | grep %s | awk -F \":\" ' { print $6 } '" % user)
    return user_home

def log(message, level=0):
    if (level == 0):
        log_level = "INFO"
    elif (level == 1):
        log_level = "WARNING"
    else:
        log_level = "ERROR"
    
    print "[%s] %s" % (log_level, message)
    
